package org.example.edusmart.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.convert.DurationUnit;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtils {

    @Value("${jwt.signKey}")
    private String signKey;

    @Value("${jwt.seconds}")
    @DurationUnit(ChronoUnit.MILLIS)
    private Duration seconds;

    /**
     * 生成token
     **/

    public String generateJwt(Integer id) {

        Date now = new Date();
        Date validity = new Date(now.getTime() + seconds.toMillis());

        Map<String, Object> claims = new HashMap<>();
        claims.put("id", id);
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, signKey)   //签名算法
                .setClaims(claims)  //内容
                .setExpiration(validity)
                .compact();
    }

    /**
     * 生成token
     **/

    public String generateJwt(Integer id, String username, String level) {

        Date now = new Date();
        Date validity = new Date(now.getTime() + seconds.toMillis());

        Map<String, Object> claims = new HashMap<>();
        claims.put("id", id);
        claims.put("username", username);
        claims.put("level", level);
        return Jwts.builder()
                .signWith(SignatureAlgorithm.ES256, signKey)
                .setClaims(claims)
                .setExpiration(validity)
                .compact();
    }

    /**
     * 解析jwt令牌
     **/

    public Claims parseJwt(String jwt) {
        return Jwts.parser()
                .setSigningKey(signKey)
                .parseClaimsJws(jwt)
                .getBody();
    }
}
